<template>
  <div class="app-container">
    <el-form ref="form" :model="form" :rules="rules" label-width="120px">
      <el-form-item prop="name" label="姓名">
        <el-input v-model="form.name" />
      </el-form-item>
      <el-form-item prop="account" label="账号">
        <el-input v-model="form.account" />
      </el-form-item>
      <el-form-item v-if="isCreate" prop="code" label="密码">
        <el-input v-model="form.code" />
      </el-form-item>
      <el-form-item label="所属 公司/项目">
        <el-cascader-panel ref="cascaderItem" v-model="expenseId" style="width: 450px;" :options="companyProjectOptions" :props="cascaderProps" clearable />
      </el-form-item>
      <el-form-item label="角色">
        <el-cascader-panel v-model="form.roles" style="width: 200px;" :options="roles" :props="roleProps" clearable />
      </el-form-item>
      <el-form-item label="头像">
        <el-input v-model="form.avatar" />
      </el-form-item>
      <el-form-item v-if="!isCreate" label="更新时间">
        {{ form.updatedAt | parseTime('{y}-{m}-{d} {h}:{i}:{s}') }}
      </el-form-item>
      <el-form-item v-if="!isCreate" label="创建时间">
        {{ form.createdAt | parseTime('{y}-{m}-{d} {h}:{i}:{s}') }}
      </el-form-item>
      <el-form-item>
        <el-button v-if="isCreate" type="primary" @click="onSubmit">添加</el-button>
        <el-button v-if="!isCreate" type="primary" @click="onSubmit">保存</el-button>
        <el-button @click="onCancel">取消</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import { selectWholeInfoById, create, update } from '@/api/user'
import { selectAll as company_selectAll } from '@/api/manage/company'
import { selectAll as project_selectAll } from '@/api/manage/project'
import { listAll as role_listAll } from '@/api/manage/role'

export default {
  data() {
    return {
      companys: [],
      projects: [],
      roles: [],
      form: {
        roles: []
      },
      isCreate: !this.$route.query.id,
      cascaderProps: {
        multiple: true, // 支持多选
        value: 'id', // 将数据结构中的id字段绑定到value。value:选择后返回的值
        label: 'name', // 将数据结构中的name字段绑定到label。label:显示文字
        children: 'children' // 将数据结构中的children字段绑定到children
      },
      roleProps: {
        multiple: true, // 支持多选
        value: 'id', // 将数据结构中的id字段绑定到value。value:选择后返回的值
        label: 'desc' // 将数据结构中的name字段绑定到label。label:显示文字
      },
      expenseId: [],
      companyProjectOptions: [],
      rules: {
        name: [
          { required: true, message: '请输入姓名', trigger: 'change' },
          { min: 1, max: 50, message: '姓名 长度应在 6 到 50 个字符之间', trigger: 'blur' }
        ],
        account: [
          { required: true, message: '请输入账号', trigger: 'change' },
          { min: 3, max: 50, message: '账号 长度应在 3 到 50 个字符之间', trigger: 'blur' }
        ],
        code: [
          { required: true, message: '请输入密码', trigger: 'change' },
          { min: 6, max: 50, message: '密码 长度应在 6 到 50 个字符之间', trigger: 'blur' }
        ]
      }
    }
  },
  created() {
    this.fetchData()
  },
  methods: {
    fetchData() {
      // 查询所有角色
      role_listAll().then(response => {
        this.roles = response.data
      })

      if (!this.isCreate) {
        selectWholeInfoById({ id: this.$route.query.id }).then(response => {
          this.form = response.data

          // 为了显示选中了哪些公司-项目，构造 expenseId 数据
          for (const company of response.data.companyList) {
            for (const project of company.projectList) {
              this.expenseId.push([company.id, project.id])
            }
          }

          this.initData() // 修改用户，用户查询成功后加载 公司 和 项目 数据
        })
      } else {
        this.initData() // 新增用户，加载 公司 和 项目 数据
      }
    },
    initData() {
      let initCompanyProject = false
      company_selectAll().then(response => {
        this.companys = response.data
        if (this.companys.length !== 0 && this.projects.length !== 0 && !initCompanyProject) {
          initCompanyProject = true
          this.initCompanyProjectOptions()
        }
      })
      project_selectAll().then(response => {
        this.projects = response.data
        if (this.companys.length !== 0 && this.projects.length !== 0 && !initCompanyProject) {
          initCompanyProject = true
          this.initCompanyProjectOptions()
        }
      })
    },
    initCompanyProjectOptions() { // 初始化公司-项目 el-cascader 数据
      for (const company of this.companys) {
        // 循环组装项目数据
        const projectArray = []
        for (const project of this.projects) {
          if (company.id === project.companyId) {
            projectArray.push({
              id: project.id,
              name: project.name
            })
          }
        }
        // 循环组装公司数据
        this.companyProjectOptions.push({
          id: company.id,
          name: company.name,
          children: projectArray
        })
      }
    },
    onSubmit() {
      this.$refs['form'].validate((valid) => {
        if (valid) {
          // 构造 companyList 数据
          const companyList = []
          let tmpCompanyId = 0 // 保存当前临时 companyId
          let tmpCompany = {} // 保存当前临时 company
          for (const index in this.expenseId) {
            if (tmpCompanyId === this.expenseId[index][0]) {
              // 如果 companyId 相同，将 project 加到 projectList 中
              tmpCompany.projectList.push({ id: this.expenseId[index][1] })
            } else {
              // 如果 companyId 不同，新建 company 并加到 projectList 中
              tmpCompany = {
                id: this.expenseId[index][0],
                projectList: [{ id: this.expenseId[index][1] }]
              }
              companyList.push(tmpCompany)
              tmpCompanyId = this.expenseId[index][0]
            }
          }
          this.form.companyList = companyList // 将构造好的数据添到 form 中

          this.form.roles = this.form.roles.map(x => +x) // 将角色数组转换为数字数组

          if (this.isCreate) {
            create(this.form).then(response => {
              this.form = response.data
              this.$message({ message: '添加成功!', type: 'success' })
              this.$router.push('/manage/users')
            })
          } else {
            update(this.form).then(response => {
              this.form = response.data
              this.$message({ message: '保存成功!', type: 'success' })
              this.$router.push('/manage/users')
            })
          }
        }
      })
    },
    onCancel() {
      this.$router.push('/manage/users')
    }
  }
}
</script>

<style scoped>
.line{
  text-align: center;
}
</style>

